package com.project.petLossSystem.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCache {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 对hash表里的字段自增1
     */
    public Long hashIncrement(final String key, final String hashKey) {
        return redisTemplate.opsForHash().increment(key, hashKey, 1);
    }

    /**
     * 获取hash表里所有键值对，返回字符串形式
     */
    public Map<String, String> hashEntries(final String key) {
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        return hashOperations.entries(key);
    }

    /**
     * 删除key
     */
    public void delete(final String key) {
        redisTemplate.delete(key);
    }

    /**
     * 覆盖list，带过期时间
     */
    public void listPutAll(final String key, List<String> values) {
        redisTemplate.delete(key); // 删除之前的
        redisTemplate.opsForList().rightPushAll(key, values);
        redisTemplate.expire(key, 1, TimeUnit.HOURS); // 过期时间
    }

    /**
     * 获取list的数据
     */
    public List<String> listGet(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }
}
